package com.ljtxxhwj.myblob.controller;


import com.ljtxxhwj.myblob.entity.DialogResult;

import com.github.pagehelper.PageInfo;
import com.ljtxxhwj.myblob.entity.ArticleWithTypeAndUname;
import com.ljtxxhwj.myblob.entity.DialogResult;
import com.ljtxxhwj.myblob.entity.User;
import com.ljtxxhwj.myblob.entity.UserWithStateName;
import com.ljtxxhwj.myblob.service.UserService;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Arrays;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

@RequestMapping("/user")
@RestController
@SessionAttributes({"user","role"})
public class UserController {

    @Autowired
    UserService userService;
    @GetMapping("/getUserById.do")
    public User getUserById(@RequestParam("userId") Integer userId) {
        System.out.println("userId = " + userId);
        return userService.selectUserById(userId);
    }

    // 更新用户信息
    @PutMapping("/updateUser.do")
    public void updateUser(@PathVariable Integer userId, @RequestBody User newUserDetails) {
        User existingUser = userService.selectUserById(userId);
        if (existingUser != null) {
            existingUser.setUserName(newUserDetails.getUserName());
            existingUser.setUserPassword(newUserDetails.getUserPassword());
            existingUser.setUserPic(newUserDetails.getUserPic());
            existingUser.setUserIntroduce(newUserDetails.getUserIntroduce());
            existingUser.setUserPhone(newUserDetails.getUserPhone());
            existingUser.setUserEmail(newUserDetails.getUserEmail());
            userService.updateUser(existingUser);
        }
    }

//    @PostMapping("/updateForm.do")
//    public String updateForm( @RequestBody Integer userId,
//                              @RequestBody String userName,
//                              @RequestBody String userIntroduce,
//                              @RequestBody String userEmail,
//                              @RequestBody String userPhone,
//                              @RequestBody String userPassword) {
//
//        userService.updateUser(userId, userName, userIntroduce, userEmail, userPhone, userPassword);
//        return "用户信息更新成功";
//    }
    @PostMapping("/updateForm.do")
    public String updateForm(@RequestBody User user) {
        System.out.println("user = " + user);
        userService.updateUser(user.getUserId(), user.getUserName(), user.getUserIntroduce(), user.getUserEmail(), user.getUserPhone(), user.getUserPassword());
        return "用户信息更新成功";
    }

    // 更新用户名
    @PatchMapping("/{userId}/name.do")
    public void updateUserName(@PathVariable Integer userId, @RequestParam String newUserName) {
        userService.updateUserName(userId, newUserName);
    }

    // 更新用户密码
    @PatchMapping("/{userId}/password.do")
    public void updateUserPassword(@PathVariable Integer userId, @RequestParam String newUserPassword) {
        userService.updateUserPassword(userId, newUserPassword);
    }

    // 更新用户头像
    @PostMapping("/updateUserPic.do")
    public void updateUserPic(HttpServletRequest request ) throws IOException {
        File file = new File("C:\\Users\\33493\\blog\\code\\myblob\\src\\main\\webapp\\img\\3.png");
        FileWriter fileWriter = new FileWriter(file);
        String fileName ="3.png";

        IOUtils.copy(request.getInputStream(),fileWriter);
        request.getInputStream().close();
        fileWriter.flush();
        fileWriter.close();
//        String relativePath = "/img/" + fileName;
//        userService.updateUserPic(1, relativePath);
//        System.out.println("newUserPic = " + newUserPic);
//        userService.updateUserPic(1, newUserPic);
    }

    // 更新用户介绍
    @PatchMapping("/{userId}/introduce.do")
    public void updateUserIntroduce(@PathVariable Integer userId, @RequestParam String newUserIntroduce) {
        userService.updateUserIntroduce(userId, newUserIntroduce);
    }

    // 更新用户电话
    @PatchMapping("/{userId}/phone.do")
    public void updateUserPhone(@PathVariable Integer userId, @RequestParam String newUserPhone) {
        userService.updateUserPhone(userId, newUserPhone);
    }

    // 更新用户邮箱
    @PatchMapping("/{userId}/email.do")
    public void updateUserEmail(@PathVariable Integer userId, @RequestParam String newUserEmail) {
        userService.updateUserEmail(userId, newUserEmail);
    }

    @PostMapping("/login.do")
    public User login(@RequestBody User user, HttpSession session) {
        return userService.login(user, session);
    }

    @GetMapping("/checkCaptcha.do")
    public boolean checkCaptcha(String captcha, HttpSession session) {
        return userService.checkCaptcha(captcha, session);
    }

    @GetMapping("/getSession.do")
    public HttpSession getSession(HttpSession session) {
        return session;
    }

    @RequestMapping("/loadWithPage.do")
    @ResponseBody
    public PageInfo<UserWithStateName> loadWithPage(@RequestParam(value = "currentPage",defaultValue = "1") Integer currentPage, @RequestParam(value = "pageSize",defaultValue = "5") Integer pageSize){
        PageInfo<UserWithStateName> pageInfo = userService.loadWithPage(currentPage,pageSize);
        return pageInfo;
    }


    @GetMapping("/findByUname.do")
    public List<UserWithStateName> findByUname(String userName){
        return userService.findByUname(userName);
    }

    @GetMapping("/backByUid.do")
    public DialogResult backByUid(Integer userId){
        DialogResult result = new DialogResult();
        try{
            userService.backByUid(userId);
            result.setMsg("恢复成功");
        }catch (Exception e){
            result.setMsg("恢复失败");
            e.printStackTrace();
        }
        return result;
    }

    @GetMapping("/closeByUid.do")
    public DialogResult closeByUid(Integer userId){
        DialogResult result = new DialogResult();
        try{
            userService.closeByUid(userId);
            result.setMsg("冻结成功");
        }catch (Exception e){
            result.setMsg("冻结失败");
            e.printStackTrace();
        }
        return result;
    }

    @GetMapping("/deleteByUid.do")
    public DialogResult deleteByUid(Integer userId){
        DialogResult result = new DialogResult();
        try{
            userService.deleteByUid(userId);
            result.setMsg("注销成功");
        }catch (Exception e){
            result.setMsg("注销失败");
            e.printStackTrace();
        }
        return result;
    }

    @GetMapping("/closeBatch.do")
    public DialogResult closeBatch(String userIds, HttpServletRequest request){
        DialogResult result = new DialogResult();
        String[] ids = userIds.split(",",0);

        try {
            for(String id : ids){
                int num = userService.closeBatch(Integer.valueOf(id));
                if(num > 0){
                    result.setMsg("冻结成功");
                }else {
                    result.setMsg("冻结失败");
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            result.setMsg("冻结失败");

        }
        return result;
    }

    @GetMapping("/deleteBatch.do")
    public DialogResult deleteBatch(String userIds, HttpServletRequest request){
        DialogResult result = new DialogResult();
        String[] ids = userIds.split(",",0);

        try {
            for(String id : ids){
                int num = userService.deleteBatch(Integer.valueOf(id));
                if(num > 0){
                    result.setMsg("注销成功");
                }else {
                    result.setMsg("注销失败");
                }
            }
     }catch (Exception e){
         e.printStackTrace();
         result.setMsg("注销失败");

     }
     return result;
    }

}
